package com.hzhjhh;

import javax.swing.*;

import org.apache.commons.lang3.StringUtils;

import java.awt.*;
import java.net.*;
import java.util.Objects;
import java.io.*;

/**
 * <p>
 * Title: HappyChat聊天系统登录程序
 * </p>
 * <p>
 * Description: 根据指定的服务器地址、用户名和密码登录聊天服务器
 * </p>
 * <p>
 * Copyright: Copyright (c) 2006
 * </p>
 * <p>
 * Filename: Login.java
 * </p>
 * 
 * @author 刘志成
 * @version 1.0
 */
public class Login extends JFrame {

	private static final long serialVersionUID = -8965773902056088264L;

	private JPanel pnlLogin;

	private JButton btLogin, btRegister, btExit;

	private JLabel lbServer, lbUserName, lbPassword, lbLogo;

	private JTextField txtUserName, txtServer;

	private JPasswordField pwdPassword;

	private String strServerIp;

	// 用于将窗口定位
	private Dimension scrnsize;

	private Toolkit toolkit = Toolkit.getDefaultToolkit();

	/**
	 * 构造登陆窗体
	 */
	public Login() {
		super("登录[HappyChat]聊天室");
		pnlLogin = new JPanel();
		this.getContentPane().add(pnlLogin);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		lbServer = new JLabel("服务器(S):");
		lbUserName = new JLabel("用户名(U):");
		lbPassword = new JLabel("口  令(P):");
		txtServer = new JTextField("127.0.0.1", 20);
//		txtServer.setText("127.0.0.1");
		txtUserName = new JTextField(20);
		pwdPassword = new JPasswordField(20);
		btLogin = new JButton("登录(L)");
		btLogin.setToolTipText("登录到服务器");
		btLogin.setMnemonic('L');
		btRegister = new JButton("注册(R)");
		btRegister.setToolTipText("注册新用户");
		btRegister.setMnemonic('R');
		btExit = new JButton("退出(X)");
		btExit.setToolTipText("退出系统");
		btExit.setMnemonic('X');
		/***********************************************************************
		 * 该布局采用手动布局 setBounds设置组件位置 * setFont设置字体、字型、字号 * setForeground设置文字的颜色
		 * * setBackground设置背景色 * setOpaque将背景设置为透明
		 */
		pnlLogin.setLayout(null); // 组件用手动布局
		pnlLogin.setBackground(new Color(52, 130, 203));

		lbServer.setBounds(50, 100, 100, 30);
		txtServer.setBounds(150, 100, 120, 25);
		lbUserName.setBounds(50, 130, 100, 30);
		txtUserName.setBounds(150, 130, 120, 25);
		lbPassword.setBounds(50, 160, 100, 30);
		pwdPassword.setBounds(150, 160, 120, 25);
		btLogin.setBounds(50, 200, 80, 25);
		btRegister.setBounds(130, 200, 80, 25);
		btExit.setBounds(210, 200, 80, 25);

		Font fontstr = new Font("宋体", Font.PLAIN, 12);
		lbServer.setFont(fontstr);
		txtServer.setFont(fontstr);
		lbUserName.setFont(fontstr);
		txtUserName.setFont(fontstr);
		lbPassword.setFont(fontstr);
		pwdPassword.setFont(fontstr);
		btLogin.setFont(fontstr);
		btRegister.setFont(fontstr);
		btExit.setFont(fontstr);

		lbUserName.setForeground(Color.BLACK);
		lbPassword.setForeground(Color.BLACK);
		btLogin.setBackground(Color.ORANGE);
		btRegister.setBackground(Color.ORANGE);
		btExit.setBackground(Color.ORANGE);

		pnlLogin.add(lbServer);
		pnlLogin.add(txtServer);
		pnlLogin.add(lbUserName);
		pnlLogin.add(txtUserName);
		pnlLogin.add(lbPassword);
		pnlLogin.add(pwdPassword);
		pnlLogin.add(btLogin);
		pnlLogin.add(btRegister);
		pnlLogin.add(btExit);

		// 设置背景图片
		ImageIcon logoImg = new ImageIcon(this.getClass().getResource("/images\\loginlogo.jpg"));
		lbLogo = new JLabel(logoImg);
		lbLogo.setBounds(0, 0, 340, 66);
		pnlLogin.add(lbLogo);
		// 设置登录窗口
		setResizable(false);
		setSize(340, 260);
		setVisible(true);
		scrnsize = toolkit.getScreenSize();
		setLocation(scrnsize.width / 2 - this.getWidth() / 2, scrnsize.height / 2 - this.getHeight() / 2);
		Image img = toolkit.getImage("images\\appico.jpg");
		setIconImage(img);

		// 三个按钮注册监听
		btLogin.addActionListener(event -> {
			String userName = txtUserName.getText();
			String password = pwdPassword.getText();
			// 账号、密码非空校验
			if (StringUtils.isAnyBlank(userName, password)) {
				JOptionPane.showMessageDialog(null, "用户名或密码不能为空");
				return;
			}
			// 校验通过，赋值服务器地址，并登录
			strServerIp = txtServer.getText();
			login();
		});
		btRegister.addActionListener(event -> {
			strServerIp = txtServer.getText();
			this.dispose();
			new Register(strServerIp);
		});
		btExit.addActionListener(event -> System.exit(0));

	}

	/**
	 * 登录事件响应方法
	 */
	@SuppressWarnings("deprecation")
	public void login() {
		// 接受客户的详细资料
		Customer data = new Customer();
		data.setCustName(txtUserName.getText());
		data.setCustPassword(pwdPassword.getText());
		ObjectOutputStream streamToServer = null;
		BufferedReader fromServer = null;
		Socket toServer = null;
		try {
			// 连接到服务器
			toServer = new Socket(strServerIp, 1001);
			streamToServer = new ObjectOutputStream(toServer.getOutputStream());
			// 写客户详细资料到服务器socket
			streamToServer.writeObject((Customer) data);
			// 读来自服务器socket的登录状态
			fromServer = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
			String status = fromServer.readLine();
			if (StringUtils.equals(status, "登录成功")) {
				new ChatRoom(data.getCustName(), strServerIp);
				this.dispose();
			} else {
				if (StringUtils.isBlank(status)) {
					status = "当前用户没有注册，请先注册后，再尝试登录";
				}
				JOptionPane.showMessageDialog(null, status);
			}
		} catch (ConnectException e1) {
			JOptionPane.showMessageDialog(null, "未能建立到指定服务器的连接!");
		} catch (InvalidClassException e2) {
			JOptionPane.showMessageDialog(null, "类错误!");
		} catch (NotSerializableException e3) {
			JOptionPane.showMessageDialog(null, "对象未序列化!");
		} catch (IOException e4) {
			JOptionPane.showMessageDialog(null, "不能写入到指定服务器!");
		} finally {
			try {
				if (Objects.nonNull(streamToServer)) {
					streamToServer.close();
				}
				if (Objects.nonNull(fromServer)) {
					fromServer.close();
				}
				if (Objects.nonNull(toServer)) {
					toServer.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
				JOptionPane.showMessageDialog(null, "资源释放异常");
			}
		}
	}

	/**
	 * 启动登陆窗体
	 * 
	 * @param args
	 */
	public static void main(String args[]) {
		new Login();
	}

}
